const serviceSql=require('../service/service')
const {v4}=require('uuid')
const {ORDERSTART_ERROR,AMOUNT_NOT_ENOUGH}=require('../error/errorType')

const orderStart=async(orderNo,userId,stadiumId)=>{
    let {affectedRows}=await serviceSql.orderInsert(orderNo,userId,stadiumId)
    if(!affectedRows){
        return ctx.app.emit('error',new Error(ORDERSTART_ERROR),ctx)
    }
    console.log(affectedRows)
    return '创建订单成功'
}

const amountOver=(period)=>{
    let time=Number(String(new Date().getTime()).slice(0,10))
    let timeOver=(time-period)/3600
    let timeData=String(timeOver).split('.')
    return timeData.length==1 ? Number(timeData[0])*15 : (Number(timeData[0])+1)*15
}

const orderEnd=async(data,id)=>{
    const [result]=await serviceSql.user(id)
    let monery=amountOver(data.time)
    if(Number(result.amount)<monery){
        return AMOUNT_NOT_ENOUGH
    }
    const orderNo=(()=>v4())()
    await serviceSql.updataUser(result.amount-monery,id)
    await serviceSql.recharge(-monery,orderNo,id,0)
    await serviceSql.orderUpdata(data.orderNo,monery)
    return '结束订单成功'
}

const orderSort=async(result)=>{
    const stadiumData=await serviceSql.stadium()
    let stadiumObj={}
    stadiumData.forEach(item=>{
        stadiumObj[item.id]=item.name
    })
    let time=Number(String(new Date().getTime()).slice(0,10))
    result.forEach(item=>{
        let timeOver
        item.stadiumName=stadiumObj[item.stadiumId]
        if(item.status==1){
            item.amount=amountOver(item.time)+'.00'
            delete item.updateAt
        }
        if(item.status==1){
            timeOver=String((time-item.time)/3600).split('.')[0]+'小时'+String(String((time-item.time-Number(String((time-item.time)/3600).split('.')[0])*3600)/60).slice('.')[0])+'分'
        }else{
            if(String((time.Overtime-item.time)/3600).split('.').length==2){
                timeOver=String((time.Overtime-item.time)/3600).split('.')[0]+'小时'+String(String((time.Overtime-item.time-Number(String((time.Overtime-item.time)/3600).split('.')[0])*3600)/60).slice('.')[0])+'分'
            }else{
                if(String(time.Overtime-item.time/60).slice('.').length==2){
                    timeOver=String(String((time.Overtime-item.time/60).slice('.')[0]))+'分'
                }else{
                    timeOver='1分'
                }
            }
            
        }
        item.time=timeOver
        delete item.Overtime
    })
    return result
}

class orderController{
    async order(ctx,next){
        const stadiumId=ctx.stadiumId
        const {id:userId}=ctx.tokenInfo
        let result=await serviceSql.orderOne(stadiumId,userId)
        if(result.length){
            // 结束订单流程
            ctx.mesg=await orderEnd(result[0],userId,ctx)
            if(ctx.mesg==AMOUNT_NOT_ENOUGH){
                ctx.app.emit('error',new Error(AMOUNT_NOT_ENOUGH),ctx)
            }
            ctx.body=[]
            await next()
        }else{
            // 创建订单流程
            const orderNo=(()=>v4())()
            ctx.mesg=await orderStart(orderNo,userId,stadiumId)
            ctx.body=[]
            await next()
        }
    }
    async orderAll(ctx,next){
        const {id}=ctx.tokenInfo
        let {page,num}=ctx.request.body
        let result=[]
        result=await serviceSql.orderAll(id)
        console.log(result)
        result=await orderSort(result)
        let resultPage=[]
        if(page&&num){
            page=Number(page)
            num=Number(num)
            if(page*num>result.length){
                let newPage = parseInt(result.length/num)
                result.forEach((item,index)=>{
                    if(index<=newPage*num && index>(newPage-1)*num){
                        resultPage.push(item)
                    }
                })
            }else{
                
                result.forEach((item,index)=>{
                    if(index<page*num && index>=(page-1)*num){
                        resultPage.push(item)
                    }
                })
            }
            
        }

        ctx.body={
            total:result.length,
            result:resultPage.length==0?result:resultPage
        }
        ctx.mesg='获取成功'
        await next()
    }
}

module.exports=new orderController()